﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Forms;

namespace ClearCache_SP2013
{
    class Program
    {
        static void Main(string[] args)
        {
            string line;
            var sbScript = new StringBuilder();
            StreamReader file = new System.IO.StreamReader(Path.GetDirectoryName(Application.ExecutablePath).ToString() + @"\clearcache.ps1");
            while ((line = file.ReadLine()) != null)
                sbScript.AppendLine(line);

            StreamWriter outputFile = new StreamWriter("ResultInfo.txt");
            var sb = new StringBuilder();

            
                // use "AddScript" to add the contents of a script file to the end of the execution pipeline.
                // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
            using (RunspaceInvoke invoker = new RunspaceInvoke())
            {
                invoker.Invoke("Set-ExecutionPolicy Unrestricted");
            } 
            Runspace runspace = RunspaceFactory.CreateRunspace();

            // open it

            runspace.Open();

            // create a pipeline and feed it the script text

            PowerShell ps = PowerShell.Create();
            ps.AddScript("Add-PsSnapin Microsoft.SharePoint.PowerShell");
            ps.AddScript(sbScript.ToString());
            ps.AddCommand("Out-String");

            Collection<PSObject> PSOutput = ps.Invoke();
                
            // loop through each output object item
            foreach (PSObject outputItem in PSOutput)
            {
                // if null object was dumped to the pipeline during the script then a null
                // object may be present here. check for null to prevent potential NRE.
                if (outputItem != null)
                {
                    //TODO: do something with the output item 
                    sb.AppendLine("--------------------------------" + System.DateTime.Now + "--------------------------------");
                    sb.AppendLine(outputItem.BaseObject.GetType().FullName);
                    sb.AppendLine(outputItem.BaseObject.ToString() + "\n");
                    outputFile.WriteLine(sb.ToString());
                }
            }
            runspace.Close();
            
        }
    }
}
